package com.shengjing.apk;

import com.shengjing.apk.update.UpdateChecker;
import com.shengjing.apk.urlprocessor.UrlProcessor;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import im.delight.android.webview.AdvancedWebView;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {

    private static final String URL = BuildConfig.URL;
    private AdvancedWebView mWebView;
    protected Uri mCameraUri;

    public static final int FILECHOOSER_RESULTCODE = 120;
    private static final int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 121;

    private ValueCallback<Uri[]> mUploadMessageForAndroid5;
    private ValueCallback<Uri> mUploadMessage;
    private String TAG = "MainActivity";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UpdateChecker.check(this);
        setContentView(R.layout.main);
        mWebView = findViewById(R.id.webview);
        mWebView.loadUrl(URL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(TAG, "shouldOverrideUrlLoading url " + url);
                UrlProcessor.INSTANCE.process(view, url);
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    url = request.getUrl().toString();
                } else {
                    url = request.toString();
                }
                Log.d(TAG, "shouldOverrideUrlLoading WebResourceRequest url " + url);
                UrlProcessor.INSTANCE.process(view, url);
                return true;
            }
        });

//        mWebView.addJavascriptInterface(this, "apkcontext");
//        mWebView.setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onGeolocationPermissionsHidePrompt() {
//                super.onGeolocationPermissionsHidePrompt();
//                Log.i(TAG, "onGeolocationPermissionsHidePrompt");
//            }
//
//            @Override
//            public void onGeolocationPermissionsShowPrompt(final String origin,
//                                                           final GeolocationPermissions.Callback callback) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(
//                        MainActivity.this);
//                builder.setMessage("共享您的位置信息?");
//                OnClickListener dialogButtonOnClickListener = new OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog,
//                                        int clickedButton) {
//                        if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
//                            callback.invoke(origin, true, true);
//                        } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
//                            callback.invoke(origin, false, false);
//                        }
//                    }
//                };
//                builder.setPositiveButton("同意", dialogButtonOnClickListener);
//                builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
//                builder.show();
//                super.onGeolocationPermissionsShowPrompt(origin, callback);
//                Log.i(TAG, "onGeolocationPermissionsShowPrompt");
//            }
//
//            // 扩展支持alert事件
//            public boolean onJsAlert(WebView view, String url, String message,
//                                     JsResult result) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(view
//                        .getContext());
//                builder.setTitle("提示").setMessage(message)
//                        .setPositiveButton("确定", null);
//                builder.setCancelable(false);
//                // builder.setIcon(R.drawable.icon);
//                AlertDialog dialog = builder.create();
//                dialog.show();
//                result.confirm();
//                return true;
//            }
//
//            // 扩展浏览器上传文件
//            // 3.0++版本
//            public void openFileChooser(ValueCallback<Uri> uploadMsg,
//                                        String acceptType) {
//                openFileChooserImpl(uploadMsg);
//            }
//
//            // 3.0--版本
//            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//                openFileChooserImpl(uploadMsg);
//            }
//
//            public void openFileChooser(ValueCallback<Uri> uploadMsg,
//                                        String acceptType, String capture) {
//                openFileChooserImpl(uploadMsg);
//            }
//
//            // For Android > 5.0
//            public boolean onShowFileChooser(WebView webView,
//                                             ValueCallback<Uri[]> uploadMsg,
//                                             WebChromeClient.FileChooserParams fileChooserParams) {
//                openFileChooserImplForAndroid5(uploadMsg);
//                return true;
//            }
//        });
    }

    @Override
    public void onBackPressed() {
        if (!mWebView.onBackPressed()) {
            return;
        }
        confirmExit();
    }

    public void confirmExit() {// 退出确认
        AlertDialog ad = new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("是否退出?")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {// 退出按钮
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        MainActivity.this.finish();// 关闭activity

                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        // 不退出不用执行任何操作
                    }
                }).create();
        ad.show();// 显示对话框
        ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0xFF576AF5);
        ad.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(0xFF576AF5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        mWebView.onActivityResult(requestCode, resultCode, intent);
//        if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage)
//                return;
//            Uri result = intent == null || resultCode != RESULT_OK ? null
//                    : intent.getData();
//            if (result != null) {
//                mUploadMessage.onReceiveValue(result);
//
//            } else {
//                mUploadMessage.onReceiveValue(mCameraUri);
//
//            }
//            mCameraUri = null;
//            mUploadMessage = null;
//
//        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
//            if (null == mUploadMessageForAndroid5)
//                return;
//            Uri result = (intent == null || resultCode != RESULT_OK) ? null
//                    : intent.getData();
//            if (result != null) {
//                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
//            } else {
//                mUploadMessageForAndroid5
//                        .onReceiveValue(new Uri[]{mCameraUri});
//            }
//            mUploadMessageForAndroid5 = null;
//            mCameraUri = null;
//
//        }
    }

    // ------------------------电话操作----------------------------------

    // -----------------------文件, 相机操作------------------------------
//    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
//        Log.i(TAG, "openFileChooserImpl ");
//        mUploadMessage = uploadMsg;
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("image/*");
//        startActivityForResult(addCameraIntent(intent), FILECHOOSER_RESULTCODE);
//    }
//
//    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
//        Log.i(TAG, "openFileChooserImplForAndroid5 ");
//        mUploadMessageForAndroid5 = uploadMsg;
//        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
//        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
//        contentSelectionIntent.setType("image/*");
//        startActivityForResult(addCameraIntent(contentSelectionIntent),
//                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
//    }
//
//    private Intent addCameraIntent(Intent intent) {
//        Log.i(TAG, "addCameraIntent ");
//        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        this.mCameraUri = createCameraUri();
//        cameraIntent.putExtra("output", this.mCameraUri);
//        cameraIntent.addCategory(Intent.CATEGORY_DEFAULT);
//
//        Intent chooserIntent = Intent.createChooser(intent, "选择要上传的文件");
//        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
//                new Intent[]{cameraIntent});
//        return chooserIntent;
//    }
//
//    protected Uri createCameraUri() {
//        File localFile = new File(Environment
//                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
//                .getAbsolutePath()
//                + File.separator + "browser-photos");
//        localFile.mkdirs();
//        return Uri.fromFile(new File(localFile.getAbsolutePath()
//                + File.separator + System.currentTimeMillis() + ".jpg"));
//    }

    // ------------------------JS交互------------------------------
    @JavascriptInterface
    public void reloadPage() {
        // 需要放到主线程中
    }

    @JavascriptInterface
    public void openSetting() {
        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS); // 系统设置
        startActivity(intent);
    }

    @JavascriptInterface
    public String getIMEI() {
        String imei = ((TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        return imei;
    }
}
